/**
 * Created by artheru on 2017/1/23.
 */
//import {createClient} from 'then-redis';
import redis from 'redis';
import bluebird from 'bluebird';
import dateFormat from 'dateformat';

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

function initDB(config) {
    const db=redis.createClient();
    db.select(1);

    var ret = {};
    ret.push = async function (message) {
        //console.log(message);
        await db.incrbyAsync('mid',1);
        let mid=await db.getAsync('mid');
        let msg={
            mid,
            messageType: message.messageType,
            messageContent: message.messageContent,
            from: message.from,
            to: message.to,
            time: new Date()
        };
        let msgstr=JSON.stringify(msg);
        await Promise.all([
            db.setAsync('msg_'+mid,msgstr),
            db.zaddAsync('conv_'+message.from+'_'+message.to, mid, msgstr),
            db.zaddAsync('conv_'+message.to+'_'+message.from, mid, msgstr),
            db.lremAsync('convs_'+message.from, 0, message.to).then(()=>db.lpush('convs_'+message.from, message.to)),
            db.lremAsync('convs_'+message.to, 0, message.from).then(()=>db.lpush('convs_'+message.to, message.from)),
            db.incrbyAsync('unread_convs_'+message.to+"_"+message.from, 1)
        ]);
        return msg;
    };

    ret.clearUnread = async function(uid, otherParty){
        db.setAsync("unread_convs_"+uid+"_"+otherParty,0);
    };

    ret.listConversations = async function(uid){
        let conv_msgs=[];
        for (let otherParty of await db.lrangeAsync('convs_'+uid,0,-1)){
            conv_msgs.push({
                otherParty,
                messages: [JSON.parse((await db.zrevrangeAsync('conv_'+uid+'_'+otherParty,0,0))[0])],
                unread: await db.getAsync('unread_convs_'+uid+'_'+otherParty)
            })
        }
        return conv_msgs;
    };

    ret.pullConversation = async function(uid, otherParty, fromMid) {
        let messages;
        if (!fromMid)
            messages=await db.zrevrangeAsync('conv_'+uid+'_'+otherParty, 0, 9);
        else{
            messages=await db.zrevrangebyscoreAsync('conv_'+uid+'_'+otherParty, "("+fromMid, 0, 'LIMIT', 0, 10);
        }
        console.log(messages);
        if (typeof messages == "boolean")
            return [];
        return messages.map((msgStr)=>JSON.parse(msgStr));
    };
    return ret;
}

export default initDB();